#!/usr/bin/env python
#coding=utf-8
from __future__ import division
import base64, os, sys
from collections import namedtuple
#获取系统时钟
CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
#def b(s):
#        return s
def _get_cputimes_fields():
    f = open('/proc/stat', 'rb')
    try:
        values = f.readline().split()[1:]
    finally:
        f.close()
    fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
    vlen = len(values)
    if vlen >= 8:
        # Linux >= 2.6.11
        fields.append('steal')
    if vlen >= 9:
        # Linux >= 2.6.24
        fields.append('guest')
    if vlen >= 10:
        # Linux >= 3.2.0
        fields.append('guest_nice')
    return fields
scputimes = namedtuple('scputimes', _get_cputimes_fields())
def cpu_times():
    f = open('/proc/stat', 'rb')
    try:
        values = f.readline().split()
    finally:
        f.close()
    fields = values[1:len(scputimes._fields) + 1]
    fields = [float(x) / CLOCK_TICKS for x in fields]
    return scputimes(*fields)
def per_cpu_times():
    cpus = []
    f = open('/proc/stat', 'rb')
    try:
        f.readline()
        #CPU = b('cpu')
        CPU = ('cpu')
        for line in f:
            if line.startswith(CPU):
                values = line.split()
                fields = values[1:len(scputimes._fields) + 1]
                fields = [float(x) / CLOCK_TICKS for x in fields]
                entry = scputimes(*fields)
                cpus.append(entry)
        return cpus
    finally:
        f.close()
